<?php
/**
 * Created by PhpStorm.
 * User: daimin
 * Date: 15/7/22
 * Time: 下午6:31
 */

namespace common\services\common;

use common\entities\common\MyscrmContractEntity;
use common\repositories\common\MyscrmContractProjectRepository;
use common\repositories\common\MyscrmOrganizationRemindRepository;
use common\services\BaseService;
use common\entities\common\MyscrmFunctionupgradeEntity;
use common\entities\common\MyscrmPackageEntity;
use common\repositories\common\MyscrmAuthorizeRepository;
use common\repositories\common\MyscrmContractRepository;
use common\repositories\common\MyscrmApplicationRepository;
use common\repositories\common\MyscrmFunctionupgradeRepository;
use common\repositories\common\MyscrmOrganizationRepository;
use common\repositories\common\MyscrmPackageRepository;
use common\services\myhtsq\ProjectService;
use linslin\yii2\curl\Curl;
use pahanini\curl\Multi;
use pahanini\curl\Request;
use Yii;
use yii\helpers\ArrayHelper;

/**
 * 授权相关的服务接口类
 * Class MyscrmAuthorizeService
 * @package common\services\common
 */
class MyscrmAuthorizeService extends BaseService {

    private $_packageRepository = null;
    private $_organizationRepository = null;
    private $_myscrmApplicationRepository;
    private $_contractRepository;
    private $_myscrmAuthorizeRepository;
    private $_myscrmFunctionupgradeRepository;

    public $qdgjAppCode = '5003';

    public function __construct(MyscrmPackageRepository $packageRepository,
                                MyscrmOrganizationRepository $organizationRepository,
                                MyscrmApplicationRepository $myscrmApplicationRepository,
                                MyscrmContractRepository $contractRepository,
                                MyscrmAuthorizeRepository $myscrmAuthorizeRepository,
                                MyscrmFunctionupgradeRepository $myscrmFunctionupgradeRepository
    ){
        $this->_packageRepository = $packageRepository;
        $this->_organizationRepository = $organizationRepository;
        $this->_myscrmApplicationRepository = $myscrmApplicationRepository;
        $this->_contractRepository = $contractRepository;
        $this->_myscrmAuthorizeRepository = $myscrmAuthorizeRepository;
        $this->_myscrmFunctionupgradeRepository = $myscrmFunctionupgradeRepository;
        parent::__construct();
    }

    /**
     * 拿到租户的所有授权的app
     * @param $orgName
     * @param bool $doFilter 是否执行过滤
     * @return static[]
     * @throws \Exception
     */
    public function getAuthorizedAppsByOrgName($orgName, $doFilter=true)
    {
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        return $this->_myscrmAuthorizeRepository->getAuthorizeAppsByOrgId($orgId, $doFilter);
    }

    /**
     * 根据app的授权码得到详情
     * @param $orgName
     * @param $authCode
     * @param bool $doFilter  表示是否过滤掉已废弃的合同，授权数为0的合同，合同数为0的应用
     * @return array|null
     * @throws \Exception
     */
    public function getAuthorizedAppByCode($orgName, $authCode){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        if (empty($authCode)) {
            throw new \Exception("应用授权码不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        return $this->_myscrmAuthorizeRepository->getAuthorizeAppByAppUniqueName($orgId, $authCode);
    }

    /**
     * 根据packageId获取其详情及合同列表
     * @param $orgName
     * @param $packageId
     * @return array
     * @throws \Exception
     */
    public function getAuthorizedPackageById($orgName, $packageId){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        if (empty($packageId)) {
            throw new \Exception("套餐包Id不能为空");
        }

        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }

        return $this->_contractRepository->getAuthorizedPackageById($orgId, $packageId);
    }


    /**
     * 获取租户的所有package详情及合同列表
     * @param $orgName
     * @return array
     * @throws \Exception
     */
    public function getAuthorizedPackagesAndContractsByOrgName($orgName){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }

        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }

        return $this->_contractRepository->getAuthorizedPackagesAndContractsByOrgId($orgId);
    }


    /**
     * 拿到租户的所有授权的package
     * @param $orgName
     * @return static[]
     * @throws \Exception
     */
    public function getAuthorizedPackagesByOrgName($orgName)
    {
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);

        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        return $this->_myscrmAuthorizeRepository->getAuthorizePackagesByOrgId($orgId);
    }

    /**
     * 返回所有的package无论其是否授权
     * @param $orgName
     * @return static[]
     * @throws \Exception
     */
    public function getAuthorizedInfoByOrgName($orgName){
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);

        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        $applicationList = $this->_myscrmApplicationRepository->getAll(false);
        $authList = $this->_myscrmAuthorizeRepository->getAuthorizeListByOrgId($orgId);
        $authUsedList = $this->_myscrmAuthorizeRepository->getUsedAuthorizeNum($orgName);
        $contractList = $this->_contractRepository->getContractByOrganizationId($orgId);
        return $this->formatAuthList($applicationList,$authList, $authUsedList, $contractList);
    }

    /**
     * 不进行curl远程获取，所以没有used_num
     * @param $orgName
     * @return static[]
     * @throws \Exception
     */
    public function getAuthorizedPackagesByOrgNameNoCurl($orgName){
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);

        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        return $this->_myscrmAuthorizeRepository->getAuthorizePackagesByOrgIdNoCurl($orgId);
    }

    /**
     * 获取老租户的应用列表
     * @param $orgName
     * @return static[]
     * @throws \Exception
     */
    public function getOldOrgPackagesByOrgName($orgName){
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);

        if(empty($orgId)){
            throw new \Exception("指定的商户不存在");
        }
        return $this->_myscrmAuthorizeRepository->getOldOrgPackagesByOrgName();
    }

    /**
     * 拿到已授权数
     */
    function getUsedAuthorizeNum($orgcode){
        return MyscrmAuthorizeRepository::getUsedAuthorizeNum($orgcode);
    }

    /**
     * 查询指定的商户是否购买掌上售楼处
     * @param $orgName string 租户名称
     * @return bool
     * @throws \Exception
     */
    public function isBuyZsslc($orgName){
        if (empty($orgName)) {
            throw new \Exception("orgName不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }
        $pkg = $this->_packageRepository->getPackageByUniqueName(MyscrmPackageEntity::ZSSLC);
        if(empty($pkg)){
            throw new \Exception("没有掌上售楼处");
        }

        $zsslcObj = $this->_packageRepository->getPackageByOrgIdAndPkgId($orgId, $pkg['id']);
        if(empty($zsslcObj)){
            return false;
        }
        return true;
    }

    /**
     * 获取合同的总授权数
     * @param $orgName
     * @param $contractId
     * @return int
     * @throws \Exception
     */
    public function getContactTotalNum($orgName, $contractId){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }
        if(empty($contractId)){
            throw new \Exception("合同ID不能为空");
        }

        $contract = $this->_contractRepository->getContractById($contractId);
        if(empty($contract) || $contract['Status'] != 1){
            throw new \Exception("不存在的合同或已作废");
        }

        return $this->_contractRepository->getContractTotalNum($orgId, $contractId);
    }

    /**
     * 根据一个授权ID获取其套餐包下所有的兄弟app的授权id
     * @param $orgName
     * @param $authorizeId
     * @return array
     * @throws \Exception
     */
    public function getAuthorizePackageAppBrothersAuthorId($orgName, $authorizeId){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return $this->_myscrmAuthorizeRepository->getAuthorizePackageAppBrothersAuthorId($orgId, $authorizeId);
    }

    /**
     * 拿到授权的总数
     * @param $authorizeId
     * @throws \Exception
     * @return int
     */
    public function getAuthorizeTotalNum($authorizeId){
        if(empty($authorizeId)){
            throw new \Exception("授权表ID不能为空");
        }

        return $this->_myscrmAuthorizeRepository->getAuthorizeTotalNum($authorizeId);

    }

    /**
     * 判断当前版本是否是MVP810版本
     * @param $orgName string 租户名称
     * @return bool
     * @throws \Exception
     */
    public function IsMvp810($orgName){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }
        return MyscrmFunctionupgradeEntity::checkIs810Version($orgId);
    }

    public function getProjectBindAppNum($orgName){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getProjectBindAppNum($orgId, true);
    }

    public function hasBindApplication($orgCode, $appCode)
    {
        if (empty($orgCode) || empty($appCode)) {
            throw new \Exception("租户企业号或应用CODE不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgCode);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::hasBindApplication($orgId, $appCode);
    }

    /**
     * 获取指定租户的授权ID对应的绑定项目ID列表
     * @param $orgName
     * @return bool|int
     * @throws \Exception
     */
    public function getProjectIds($orgName){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getProjectIds($orgId, true);
    }

    /**
     * 获取所有应用
     * @return array
     */
    public function getAllApplications()
    {
        $applicationList = $this->_myscrmApplicationRepository->getAll();
        return $this->formatApplicationList($applicationList);
    }

    /**
     * @param $applicationList \common\entities\common\MyscrmApplicationEntity[]
     * @param $authList \common\entities\common\MyscrmOrganizationToAuthorizeEntity[]
     * @param $authUsedList array [[AuthorizeId=>count],...]
     * @param $contractList \common\entities\common\MyscrmContractEntity[]
     * @return array [应用名称 =>[应用内容],...]
     */
    private function formatAuthList($applicationList, $authList, $authUsedList, $contractList)
    {

        /** @var \common\entities\common\MyscrmContractEntity[] $contractListIndexByContractId */
        $contractListIndexByContractId = ArrayHelper::index($contractList, 'ContractId');
        /** @var \common\entities\common\MyscrmApplicationEntity[] $applicationIndexByIdList */
        $applicationIndexByIdList = ArrayHelper::index($applicationList, 'ApplicationId');
        $result = [];
        foreach ($authList as $auth) {
            $contract = $contractListIndexByContractId[$auth->ContractId];
            if(empty($contract)
                || $contractListIndexByContractId[$auth->ContractId]->Status == 2
                || MyscrmContractEntity::isContractOverdue($contract)){
                continue;
            }

            if (!isset($applicationIndexByIdList[$auth->ApplicationId])) {
                continue;
            }

            $appName = $applicationIndexByIdList[$auth->ApplicationId]->FriendlyName;
            $authUsedCount = isset($authUsedList[$auth->Id]) ? $authUsedList[$auth->Id] : 0;
            if (!isset($result[$appName])) {

                $authArray = [
                    'id' => $auth->Id,
                    'friendly_name' => $appName,
                    'unique_name' => $applicationIndexByIdList[$auth->ApplicationId]->UniqueName,
                    'total_num' => $auth->TotalNum,
                    'used_num' => $authUsedCount,
                ];
                $result[$appName] = $authArray;
            }else{
                $result[$appName]['total_num'] += $auth->TotalNum;
                $result[$appName]['used_num'] += $authUsedCount;
            }
        }
        return $result;
    }

    /**
     * @param $applicationList array|\common\entities\common\MyscrmApplicationEntity[]
     * @return array
     */
    private function formatApplicationList($applicationList)
    {
        $result = [];
        foreach ($applicationList as $key => $application) {
            if ($application['IsUnAuth'] == 1) {//移除在授权页不显示的应用（微支付商城、云服务、新版微楼书）
                unset($applicationList[$key]);
                continue;
            }
            $applicationArray = [
                'id'            => $application->ApplicationId,
                'friendly_name' => $application->FriendlyName,
                'unique_name'   => $application->UniqueName,
                'count'         => 0,
            ];
            $result[] = $applicationArray;

            //加上渠道管家旗舰版
            if ($application->UniqueName == $this->qdgjAppCode) {
                $applicationArray = [
                    'id'            => $application->ApplicationId,
                    'friendly_name' => '渠道管家(旗舰版)',
                    'unique_name'   => $application->UniqueName,
                    'IsQdAdvanced'  => 1,
                ];
                $result[] = $applicationArray;
            }
        }

        return $result;
    }

    /**
     * 获取指定租户的授权ID对应的绑定项目ID列表
     * @param $orgCode
     * @param $keyword
     * @return bool|int
     * @throws \Exception
     */
    public function getNeedRenewedProjects($orgCode, $keyword)
    {
        if (empty($orgCode)) {
            throw new \Exception("租户企业号不能为空");
        }

        $orgId = $this->_organizationRepository->getOrgId($orgCode);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        $arrProjectToAuthorize = MyscrmAuthorizeRepository::getNeedRenewedProjects($orgCode, $keyword);

        if($arrProjectToAuthorize) {
            //按状态排序(即将过期、已过期、正常)
            ArrayHelper::multisort($arrProjectToAuthorize, "Status", SORT_ASC);
        }

        return $arrProjectToAuthorize;
    }

    /**
     * 续签汇报第一步列表
     * @param $contractId
     * @param $organizationId
     * @param $keyword
     * @param $projectId
     * @return array
     * @throws \Exception
     */
    public function getRemindDetailsStepOne($organizationId, $keyword, $contractId, $projectId)
    {
        if (empty($contractId) && empty($projectId)) {
            throw new \Exception("合同ID项目ID不能同时为空");
        }

        $orgEntity = $this->_organizationRepository->getOrgById($organizationId);
        if(empty($orgEntity)){
            throw new \Exception("商户不存在");
        }

        $needRenewDataList = MyscrmAuthorizeRepository::getNeedRenewedProjects($orgEntity->UniqueName, $keyword, $contractId, $projectId);

        if(empty($needRenewDataList)){
            return [];
        }

        /** @var MyscrmOrganizationRemindRepository $organizationRemindRepository */
        $organizationRemindRepository = \Yii::createObject(MyscrmOrganizationRemindRepository::className());

        $ret = [];
        foreach ($needRenewDataList as &$needRenewData){
            $projectId = $needRenewData['ProjectId'];
            $appCode = $needRenewData['AppCode'];
            $projectContractId = $needRenewData['ContractId'];

            //移除不要的字段
            unset($needRenewData['IsXq']);
            unset($needRenewData['RenewCount']);
            unset($needRenewData['RenewRecords']);

            $remindDetails = $organizationRemindRepository->getRemindDetails($projectContractId);
            $remindDetailsGroupBy = [];
            foreach ($remindDetails as $remindDetail){
                $remindProjectId = $remindDetail['projectId'];
                $remindAppCode = $remindDetail['appCode'];

                $remindDetailsGroupBy[$projectContractId][$remindProjectId][$remindAppCode]['isXq'] = $remindDetail['isXq'];
                $remindDetailsGroupBy[$projectContractId][$remindProjectId][$remindAppCode]['renewStatus'] = $remindDetail['renewStatus'];
                $remindDetailsGroupBy[$projectContractId][$remindProjectId][$remindAppCode]['noRenewReason'] = $remindDetail['noRenewReason'];
            }

            //装拼续签汇报结果
            $needRenewData['IsXq'] = null;
            $needRenewData['XqResult'] = null;
            if(isset($remindDetailsGroupBy[$projectContractId][$projectId][$appCode]['isXq'])){
                $needRenewData['IsXq'] = $remindDetailsGroupBy[$projectContractId][$projectId][$appCode]['isXq'];

                if($needRenewData['IsXq'] == 1){
                    $needRenewData['XqResult'] = $remindDetailsGroupBy[$projectContractId][$projectId][$appCode]['renewStatus'];
                }else{
                    $needRenewData['XqResult'] = $remindDetailsGroupBy[$projectContractId][$projectId][$appCode]['noRenewReason'];
                }
            }

            $ret[] = $needRenewData;
        }

        return $ret;
    }

    /**
     * 获取需要续签的合同列表
     * @param $orgCode
     * @return bool
     * @throws \Exception
     */
    public function getNeedRenewContractList($orgCode)
    {
        if (empty($orgCode)) {
            throw new \Exception("租户企业号不能为空");
        }

        $orgId = $this->_organizationRepository->getOrgId($orgCode);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getNeedRenewContractList($orgCode);
    }

    public function getOverdueOr30daysOverdueContracts($orgName){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getOverdueOr30daysOverdueContracts($orgName);
    }

    public function getApplicationAuthInfo($orgName, $contractId){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getApplicationAuthInfo($orgName, $contractId);
    }

    /**
     * 获取指定的应用
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getApplicationListByApplicationCodes()
    {
        return $this->_myscrmAuthorizeRepository->getApplicationListByApplicationCodes();
    }

    public function getProjectApplicationRelation($orgName, $projects){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getProjectApplicationRelation($orgName, $projects);
    }

    public function getApplicationToProjectToAuthorizes($orgName, $contractId){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getApplicationToProjectToAuthorizes($orgName, $contractId);
    }

    public function SaveBindingAuth($orgName, $auth){
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgName);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::SaveBindingAuth($orgName, $auth);
    }

    /**
     * 获取项目禁用/已禁用列表
     * @param $orgCode
     * @param int $status
     * @param string $projectName
     * @param int $pageIndex
     * @param int $pageSize
     * @return bool|int
     * @throws \Exception
     */
    public function getProjectAuthContractList($orgCode, $projectName = '', $status = 0, $pageIndex = 1, $pageSize = 10)
    {
        if (empty($orgCode)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgCode);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getProjectAuthContractList($orgCode, $projectName, $status, $pageIndex, $pageSize);
    }

    /**
     * 更改禁用状态
     * @param $disableItems 需要禁用或者开启的数组
     * @return bool
     * @throws \Exception
     */
    public function changeDisable($disableItems)
    {
        $orgCode = isset($disableItems[0]['orgCode']) ? $disableItems[0]['orgCode'] : '';
        if (empty($orgCode)) {
            throw new \Exception("租户企业号不能为空");
        }
        $orgId = $this->_organizationRepository->getOrgId($orgCode);
        if (empty($orgId)) {
            throw new \Exception("商户不存在");
        }
        $res = MyscrmAuthorizeRepository::changeDisable($orgCode, $disableItems);
        if (true === $res) {
            return true;
        } else {
            return $this->setAndReturn(__LINE__, $res);
        }
    }

    public function getNewestReason($orgCode, $p_projectId, $applicationCode)
    {
        if (empty($orgCode)) {
            throw new \Exception("租户企业号不能为空");
        }

        $orgId = $this->_organizationRepository->getOrgId($orgCode);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getNewestReason($orgCode, $p_projectId, $applicationCode);
    }

    public function getListByProjectIdApplicationCode($orgCode, $p_projectId, $applicationCode)
    {
        if (empty($orgCode)) {
            throw new \Exception("租户企业号不能为空");
        }

        $orgId = $this->_organizationRepository->getOrgId($orgCode);
        if(empty($orgId)){
            throw new \Exception("商户不存在");
        }

        return MyscrmAuthorizeRepository::getListByProjectIdApplicationCode($orgCode, $p_projectId, $applicationCode);
    }

    /**
     * 根据合同ID应用代码获取项目绑定记录
     * @param $orgName
     * @param $contractId
     * @param $applicationCode
     * @param $keyword
     * @param $pageIndex
     * @param $pageSize
     * @param $isQdAdvanced
     * @return bool
     * @throws \Exception
     */
    public function getProjectBindRecordByContractIdApplicationCode($orgName, $contractId, $applicationCode, $keyword, $pageIndex, $pageSize, $isQdAdvanced)
    {
        if (empty($orgName)) {
            throw new \Exception("租户企业号不能为空");
        }

        if (empty($contractId)) {
            throw new \Exception("合同ID不能为空");
        }

        return MyscrmAuthorizeRepository::getProjectBindRecordByContractIdApplicationCode($orgName, $contractId, $applicationCode, $keyword, $pageIndex, $pageSize, $isQdAdvanced);
    }

    /**
     * 根据授权ID获取已绑定的项目
     * @param $orgId
     * @param $authorizeId
     * @return bool|array
     * @throws \Exception
     */
    public function getProjectByAuthorizeId($orgId, $authorizeId)
    {
        $orgInfo = $this->_organizationRepository->getOrgById($orgId);
        if (empty($orgInfo)) {
            return [];
        }

        return MyscrmAuthorizeRepository::getProjectByAuthorizeId($orgInfo->UniqueName, $authorizeId);
    }

    /**
     * 判断项目是否被禁用，并返回禁用原因
     * @param $orgId
     * @param $projectId
     * @param $applicationCode
     * @return bool
     * @throws \Exception
     */
    public function getProjectIsDisableAndReason($orgId, $projectId, $applicationCode)
    {
        $orgInfo = $this->_organizationRepository->getOrgById($orgId);
        if (empty($orgInfo)) {
            return [];
        }

        return MyscrmAuthorizeRepository::getProjectIsDisableAndReason($orgInfo->UniqueName, $projectId, $applicationCode);
    }

    /**
     * 获取项目应用合同关系数据
     * @param $orgId
     * @return array
     * @throws \Exception
     */
    public function getContractApplicationProject($orgId)
    {
        $orgInfo = $this->_organizationRepository->getOrgById($orgId);
        if (empty($orgInfo)) {
            return [];
        }

        return MyscrmAuthorizeRepository::getContractApplicationProject($orgInfo->UniqueName);
    }

    /**
     * 通过接口获取项目应用的授权信息
     * @param $orgCodes
     * @return array
     * @throws \Exception
     */
    public function batchGetContractApplicationProject($orgCodes)
    {
        return MyscrmAuthorizeRepository::batchGetContractApplicationProject($orgCodes);
    }

    /**
     * 从DB中获取项目应用的授权信息
     * @param array $orgCodes
     * @return array
     * @throws \yii\base\InvalidConfigException
     */
    public function getOrgContractApplicationProject($orgCodes = [])
    {
        /* @var $myscrmContractProjectRepository MyscrmContractProjectRepository */
        $myscrmContractProjectRepository=\Yii::createObject(MyscrmContractProjectRepository::className());
        $data=$myscrmContractProjectRepository->getAllByOrgCodes($orgCodes);
        $result=[];
        foreach($data as $item){
            if (empty($item["ProjId"])) {
                continue;
            }
            $orgcode=$item["orgcode"];
            if(isset($result[$orgcode])){
                array_push($result[$orgcode],$item);
            }else{
                $result[$orgcode]=[$item];
            }
        }
        return $result;
    }

    public function syncContractApplicationProject()
    {
        /* @var $myscrmOrganizationService MyscrmOrganizationService */
        $myscrmOrganizationService=\Yii::createObject(MyscrmOrganizationService::className());
        $data = $myscrmOrganizationService->getAllAuthProject("", "", "", "");
        $organizationIds = ArrayHelper::getColumn($data, 'OrganizationId');
        $organizationIds = array_unique($organizationIds);

        /* @var $myscrmOrganizationRepository MyscrmOrganizationRepository */
        $myscrmOrganizationRepository=\Yii::createObject(MyscrmOrganizationRepository::className());
        $orgList=$myscrmOrganizationRepository->getListByIds($organizationIds, false);
        $orgCodes = ArrayHelper::getColumn($orgList, 'UniqueName');

        if(empty($orgCodes)){
            return [];
        }
        $appCfg = ArrayHelper::getValue(\Yii::$app->params, "QmyxRefactorInterface", null);
        if(empty($appCfg)){
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }

        $nowtimestamp = time();
        $siteUrl = rtrim($appCfg['url'], '/');

        $multi = new Multi();
        $multi->stackSize = count($orgCodes);

        $requests= [];
        foreach ($orgCodes as $orgCode){
            $param = [
                'r' => 'project-auth/sync-contract-project',
                'appid' => $appCfg["appId"],
                't' => $nowtimestamp,
                'sign' => md5($nowtimestamp."#".$appCfg['appSecret']),
                'orgcode' => $orgCode
            ];
            $url = $siteUrl . '?' . http_build_query($param);


            $requests[$orgCode] = new Request();
            $requests[$orgCode]->setUrl($url);

            $multi->add($requests[$orgCode]);
        }

        $multi->execute();

        $result = [];
        foreach ($requests as $orgCode => $request) {
            $response = $request->getResponse();
            /* @var $response \pahanini\curl\Response */
            if($res = $response->getContent()){
                $data = json_decode($res, true);
                if($data['retCode'] == 0){
                    $result[$orgCode] = $data;
                }
            }
        }

        return $result;
    }

    /**
     * @return array
     */
    public function getExtraApplications()
    {
        $applicationList = $this->_myscrmApplicationRepository->getExtraApplications();
        return $this->formatApplicationList($applicationList);
    }

    /**
     * @param $orgcode
     * @param $contractCode
     * @return array|null
     */
    function getContractAuthorizeCount($orgcode, $contractCode)
    {
        if (empty($orgcode)) {
            return [];
        }

        return MyscrmAuthorizeRepository::getContractAuthorizeCount($orgcode, $contractCode);
    }
}
